package com.ea.eadp.nexus.test.pageDefinition;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;

import com.ea.eadp.nexus.test.common.PageOperation;
import com.ea.eadp.nexus.test.common.SystemProperties;
import com.ea.eadp.nexus.test.common.TestUtil;

public class XfinitySigninPage extends BasePage {
    public static final String DEFAULTURI = baseUri + TestUtil.SigninXfinityConnectURI();
    public static final String REDIRECTURI = SystemProperties.instance().getProperty(SystemProperties.RedirectUri);
    public static final String CONTINUEWITHOUTEAACCOUNTURI = "localhost";

    public static final String XPATHINCORRECTEMAILORPASSWORD = "//div[@id='panel-error-login']/div[1]";
    public static final String ERRORMESSAGEINCORRECTEMAILORPASSWORD = "Your Email or Password is incorrect. Please try again.";
    public static final String ERRORMESSAGEMISSINGMAILORPASSWORD = "Email or password must be specified.";
    public static final String XPATHNOTMEETREQUIREMENT = "//div[@id='panel-error-login']/div[1]";
    public static final String ERRORMESSAGENOTMEETREQUIREMENT =
 "Sorry, you don't meet the requirements to access Xfinity Games. Would you like to continue without an EA Account to play E rated games only?";
    public static final String XPATHMISSINGCAPTCHA = "//div[@id='panel-error-captcha']/div[1]";
    public static final String ERRORMESSAGEMISSINGCAPTCHA = "Missing CAPTCHA verification.";
    public static final String XPATHNOTCHECKINGTOS = "//div[@id='panel-error-login-tos']/div[1]";
    public static final String ERRORMESSAGENOTCHECKINGTOS = "You must accept the Xfinity Games Terms of use.";

    private static final String readAcceptDivXpath = "//div[@id='panel-login']/div[6]";
    private static final String readAcceptCheckboxXpath = readAcceptDivXpath + "/span";
    private static final String signupLinkXpath = "//div[@id='container']/div[1]/span/a";
    private static final String signinButtonXpath = "//div[@id='panel-login']/div[7]/a/span";
    private static final String signinButtonXpath2 = "//div[@id='panel-login']/div[8]/a/span";
    private static final String forgetPasswordLinkXpath = "//div[@id='panel-login']/div[4]/a";
    private static final String continueWithoutAnEAAccountXpath = XPATHNOTMEETREQUIREMENT + "/a";
    private static final String showHidePasswordXpath = "//div[@id='panel-login']/div[3]/div/label";

    private static final String headerXpath = "//div[@id='container']/div[1]/span";
    private static final String titleXpath = "//div[@id='panel-header']/div/div";
    private static final String emailPlaceHolderXpath = "//div[@id='panel-login']/div[1]/div[2]/div[2]/div[2]";
    private static final String passwordPlaceHolderXpath = "//div[@id='panel-login']/div[2]/div[2]/div[2]/div[2]";
    private static final String tosXpath = "//div[@id='panel-login']/div[6]/label";

    public XfinitySigninPage(WebDriver driver) {
        super(driver, XfinitySigninPage.class);
        this.setUri(DEFAULTURI);
    }

    public void validateStrings(boolean prepopulatedEmail) throws Exception {
        validatePageContent(headerXpath, "Don't have an EA Account? Sign Up");
        validatePageContent(titleXpath, "Log in to your EA Account\nto access XFINITY Games");
        if (!prepopulatedEmail) validatePageContent(emailPlaceHolderXpath, "Email");
        validatePageContent(passwordPlaceHolderXpath, "Password");
        validatePageContent(tosXpath, "I have read and accept XFINITY Games Terms of Use");
    }

    public void setSigninEmail(final String email) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(email);
        PageOperation.SendKeyToElementAfterWait(driver, "email", email);
    }

    public void setSigninPassword(final String password) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(password);
        PageOperation.SendKeyToElementAfterWait(driver, "password", password);
    }

    public void clickShowHidePassword(boolean showPassword) {
        String[] texts = null;
        if (showPassword)
            texts = new String[] { "show", "hide" };
        else
            texts = new String[] { "hide", "show" };
        Assert.assertEquals(driver.findElement(By.xpath(showHidePasswordXpath)).getText(), texts[0]);
        driver.findElement(By.xpath(showHidePasswordXpath)).click();
        Assert.assertEquals(driver.findElement(By.xpath(showHidePasswordXpath)).getText(), texts[1]);
    }

    public void setCaptcha(final String value) {
        driver.switchTo().window(this.operationWindowHandle);
        log.info(value);
        PageOperation.SendKeyToElementAfterWait(driver, "captcha", value);
    }

    public void checkboxReadAccept(final boolean check) {
        driver.switchTo().window(this.operationWindowHandle);
        if (check && !driver.findElement(By.id("readAccept")).isSelected())
            driver.findElement(By.xpath(readAcceptCheckboxXpath)).click();
        else if (!check && driver.findElement(By.id("readAccept")).isSelected())
            driver.findElement(By.xpath(readAcceptCheckboxXpath)).click();
    }

    public void clickSignupLink() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath(signupLinkXpath)).click();
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1000);
            if (TestUtil.getCurrentUrl(driver).contains("p/xfinity/create?")) return;
        }
        throw new Exception("validate goes to redirect uri.");
    }

    public void clickToSigninComplete() throws Exception {
        clickToSignin();
        validateRedirect();
    }

    public void clickToSigninComplete2() throws Exception {
        clickToSignin2();
        validateRedirect();
    }

    public void clickToSigninAndValidate(final String path, final String regex) throws Exception {
        clickToSignin();
        validatePageContent(path, regex);
    }

    public void clickToSigninAndValidate2(final String path, final String regex) throws Exception {
        clickToSignin2();
        validatePageContent(path, regex);
    }

    public void clickContinueWithoutAnEAAccount() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath(continueWithoutAnEAAccountXpath)).click();
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1000);
            if (TestUtil.getCurrentUrl(driver).contains(CONTINUEWITHOUTEAACCOUNTURI)) {
                if (!TestUtil.getCurrentUrl(driver).contains("?code=")) return;
                else break;
            }
        }
        throw new Exception("validate goes to redirect uri.");
    }

    public void clickToResetPassword() throws Exception {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath(forgetPasswordLinkXpath)).click();
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1000);
            for(String handle : driver.getWindowHandles()) {
                driver.switchTo().window(handle);
                if (TestUtil.getCurrentUrl(driver).contains("/resetPassword?") && driver.getWindowHandles().size() == 2) return;
            }
        }
        throw new Exception("validate goes to 'reset password' page.");
    }

    private void clickToSignin() {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath(signinButtonXpath)).click();
    }

    private void clickToSignin2() {
        driver.switchTo().window(this.operationWindowHandle);
        driver.findElement(By.xpath(signinButtonXpath2)).click();
    }

    private void validateRedirect() throws Exception {
        for (int i = 0; i < 5; i++) {
            Thread.sleep(1000);
            if ((TestUtil.getCurrentUrl(driver).contains(REDIRECTURI) || TestUtil.getCurrentUrl(driver).contains("s2")) && TestUtil.getCurrentUrl(driver).contains("?code=")) return;
        }
        throw new Exception("validate goes to redirect uri.");
    }
}
